import unreal

# 0. 准备模型
# 创建一个模型
# 创建一个level sequence
# 把模型添加进这个level sequence

# -----------------------------------------------------------------------------
# 1. 准备数据 (请替换为您自己的数据)
# -----------------------------------------------------------------------------
time = [0.0, 0.5, 1.0, 1.5, 2.0]  # 时间（秒）
positions = [
    (0, 0, 100),
    (100, 50, 120),
    (200, 150, 150),
    (300, 300, 180),
    (400, 500, 200)
]  # 位置 (X, Y, Z) - 单位：厘米
rotations = [
    (0, 0, 0),
    (10, 5, 0),
    (20, 10, 5),
    (30, 15, 10),
    (40, 20, 15)
]  # 旋转 (Roll, Pitch, Yaw) - 单位：度

# -----------------------------------------------------------------------------
# 2. 获取关卡中的Actor
# -----------------------------------------------------------------------------
editor_world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world()
actor_label = "My_Airplane" # 【请确保关卡中Actor的标签与此一致】
actor_to_animate = None
all_actors = unreal.GameplayStatics.get_all_actors_of_class(editor_world, unreal.Actor)
for actor in all_actors:
    if actor.get_actor_label() == actor_label:
        actor_to_animate = actor
        break

if not actor_to_animate:
    unreal.log_error(f"错误：在关卡中找不到名为 '{actor_label}' 的Actor。")
else:
    unreal.log(f"成功找到Actor: {actor_to_animate.get_actor_label()}")

    # -----------------------------------------------------------------------------
    # 3. 创建或加载关卡序列
    # -----------------------------------------------------------------------------
    sequence_name = "Airplane_Animation_Sequence"
    sequence_path = "/Game/Sequences/" # 【可以自定义路径】

    asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
    level_sequence = unreal.load_asset(sequence_path + sequence_name)
    if not level_sequence:
        level_sequence = asset_tools.create_asset(
            asset_name=sequence_name,
            package_path=sequence_path,
            asset_class=unreal.LevelSequence,
            factory=unreal.LevelSequenceFactoryNew()
        )
        unreal.log(f"已创建新的关卡序列: {sequence_path}{sequence_name}")

    # -----------------------------------------------------------------------------
    # 4. 将Actor绑定到序列
    # -----------------------------------------------------------------------------
    binding = level_sequence.add_possessable(actor_to_animate)
    if not binding:
        binding = level_sequence.find_possessable(actor_to_animate)

    # -----------------------------------------------------------------------------
    # 5. 获取或创建变换轨道
    # -----------------------------------------------------------------------------
    transform_track = None
    for track in binding.get_tracks():
        if isinstance(track, unreal.MovieScene3DTransformTrack):
            transform_track = track
            break
    if not transform_track:
        transform_track = binding.add_track(unreal.MovieScene3DTransformTrack)

    # -----------------------------------------------------------------------------
    # 6. 设置轨道、范围和关键帧
    # -----------------------------------------------------------------------------
    # 清空旧数据，防止重复运行脚本时数据叠加
    for section in transform_track.get_sections():
        transform_track.remove_section(section)
    transform_section = transform_track.add_section()
    
    # 设置帧率和播放范围
    frame_rate = unreal.FrameRate(30, 1) # 假设30fps
    level_sequence.set_display_rate(frame_rate)
    level_sequence.set_playback_start(time[0]) # 设置播放开始时间（秒）
    level_sequence.set_playback_end(time[-1])   # 设置播放结束时间（秒）

    # 设置数据片段的范围（需要用帧）
    fps = frame_rate.numerator / frame_rate.denominator
    start_frame = int(round(time[0] * fps))
    end_frame = int(round(time[-1] * fps))
    transform_section.set_range(start_frame, end_frame)

    # 获取位置和旋转的通道
    channels = transform_section.get_all_channels()
    location_x_channel, location_y_channel, location_z_channel = channels[0], channels[1], channels[2]
    rotation_x_channel, rotation_y_channel, rotation_z_channel = channels[3], channels[4], channels[5]

    unreal.log("开始添加关键帧...")
    # 【修正】使用 ScopedEditorTransaction 来创建可撤销的编辑器操作
    with unreal.ScopedEditorTransaction("Add Keys to Airplane Sequence") as trans:
        for i in range(len(time)):
            current_time = time[i]
            current_pos = positions[i]
            current_rot = rotations[i]

            frame_number = int(round(current_time * fps))
            frame_value = unreal.FrameNumber(frame_number)

            location_x_channel.add_key(frame_value, current_pos[0])
            location_y_channel.add_key(frame_value, current_pos[1])
            location_z_channel.add_key(frame_value, current_pos[2])

            rotation_x_channel.add_key(frame_value, current_rot[0]) # Roll
            rotation_y_channel.add_key(frame_value, current_rot[1]) # Pitch
            rotation_z_channel.add_key(frame_value, current_rot[2]) # Yaw

    unreal.log("关键帧添加完成！")

    # -----------------------------------------------------------------------------
    # 7. 刷新Sequencer窗口
    # -----------------------------------------------------------------------------
    # 通过资产编辑器子系统打开序列，以刷新UI
    unreal.get_editor_subsystem(unreal.AssetEditorSubsystem).open_editor_for_assets([level_sequence])

    unreal.log("脚本执行完毕，已打开或刷新Sequencer窗口。")
